import { pageInfo } from './PageInfo';
import * as lib from 'libdjvulibre.so';
import image from '@ohos.multimedia.image';

export class DjvuDocument {
  private readonly name;
  private readonly path;

  constructor(name: string, path: string) {
    this.name = name;
    this.path = path;
  }

  open(): boolean {
    const ret = lib.open(this.name, this.path);
    return ret == 1;
  }

  async openAsync(): Promise<boolean> {
    const ret = await lib.openAsync(this.name, this.path);
    return ret == 1;
  }

  pageSize(): number {
    return lib.pageSize();
  }

  pageSizeAsync(): Promise<number> {
    return lib.pageSizeAsync();
  }

  async pageInfo(index: number, scale: number, color: boolean = false): Promise<pageInfo> {
    const samples = color ? 0 : 1;
    const data = lib.pageInfo(index, scale, samples);
    const buffer: ArrayBuffer = data.pixel;
    const pixel = await image.createPixelMap(buffer, { size: { width: data.width, height: data.height } });
    const result: pageInfo = {
      pixel,
      dpi: data.dpi,
      width: data.width,
      height: data.height
    };
    return result;
  }

  async pageInfoAsync(index: number, scale: number, color: boolean = false): Promise<pageInfo> {
    const samples = color ? 0 : 1;
    const data = await lib.pageInfoAsync(index, scale, samples);
    const buffer: ArrayBuffer = data.pixel;
    const pixel = await image.createPixelMap(buffer, { size: { width: data.width, height: data.height } });
    const result: pageInfo = {
      pixel,
      dpi: data.dpi,
      width: data.width,
      height: data.height
    };
    return result;
  }

  release(): void {
    lib.release();
  }

  async releaseAsync(): Promise<void> {
    await lib.releaseAsync();
  }
}